import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/evaluation/evaluationOverviewResult.dart';
import 'package:ichinesereader/models/report/evaluationLevelChartData.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/evaluationAccuracy.dart';
import 'package:ichinesereader/widgets/charts/evaluationLevelAverageStackedLines.dart';
import 'package:dropdown_search/dropdown_search.dart';

import '../../themes/appTheme.dart';

class QuickReviewOverviewCharts extends StatefulWidget {
  @override
  _QuickReviewOverviewChartsState createState() =>
      _QuickReviewOverviewChartsState();
}

class _QuickReviewOverviewChartsState extends State<QuickReviewOverviewCharts> {
  final box = Hive.box('appconfig');
  final myKey = GlobalKey<DropdownSearchState<StudentList>>();
  final ReportsController controller = Get.find();
  String classId = '';
  String _levelStandard = Constants.levelStandardTypes[0];
  List<StudentList> _selectedStudentLists = [];

  @override
  void initState() {
    classId = box.get(CacheManagerKey['currentclass'].toString());
    Future.delayed(Duration(milliseconds: 100), (() {
      controller.fetchLibraryOverviewClassData(classId);
    }));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build teacher quick review overview charts page');

    onSelectStudent(List<StudentList> students) {
      _selectedStudentLists = students;
      controller.refresLibraryOverviewData(classId);
    }

    return Center(
      child: Column(
        children: [
          Row(
            children: [
              controller.obx(
                (data) {
                  if (controller.quickReviewOverviewResult.value.studentList !=
                      null) {
                    return Expanded(
                      child: DropdownSearch<StudentList>.multiSelection(
                        itemAsString: (item) {
                          return item.userName.toString();
                        },
                        dropdownDecoratorProps: DropDownDecoratorProps(
                          dropdownSearchDecoration: InputDecoration(
                            labelText: "Choose Student".tr,
                            labelStyle:
                                TextStyle(color: Get.theme.primaryColorLight),
                          ),
                        ),
                        popupProps: PopupPropsMultiSelection.menu(
                            showSearchBox: true,
                            itemBuilder: (ctx, item, isSelected) {
                              return ListTile(
                                  tileColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme4
                                      : Get.theme.primaryColorLight,
                                  selected: false,
                                  title: Text(item.userName.toString()));
                            }),
                        key: myKey,
                        items: controller.quickReviewOverviewResult.value
                            .studentList as List<StudentList>,
                        selectedItems: [],
                        onChanged: onSelectStudent,
                      ),
                    );
                  } else {
                    return Text('');
                  }
                },
                //onLoading: Center(child: CircularProgressIndicator()),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Container(
                    height: 48,
                    width: 180,
                    child: FormBuilderChoiceChip(
                      decoration: InputDecoration.collapsed(
                        hintText: '',
                        border: InputBorder.none,
                      ),
                      spacing: 8,
                      labelStyle: TextStyle(
                        color: Get.isDarkMode
                            ? Colors.black
                            : Theme.of(context).primaryColorLight,
                        fontSize: 15,
                        letterSpacing: 0.8,
                      ),
                      backgroundColor: Get.isDarkMode
                          ? Get.theme.primaryColor
                          : Colors.blueGrey,
                      selectedColor: Get.isDarkMode
                          ? (Colors.white)
                          : Theme.of(context).primaryColorDark,
                      name: 'level_standard_types',
                      onChanged: (value) {
                        if (value == null) return;
                        _levelStandard = value.toString();
                        controller.fetchLibraryOverviewClassData(classId);
                      },
                      initialValue: Constants.levelStandardTypes[0],

                      ///这里暂时去掉yct,hsk
                      options: Constants.levelStandardTypes
                          .where((element) =>
                              element != 'YCT' &&
                              element != 'HSK' &&
                              element != "ACTFL")
                          .map((state) => FormBuilderChipOption<String>(
                                value: state,
                                child: Text(
                                  state.toString(),
                                ),
                              ))
                          .toList(),
                    )),
              ],
            ),
          ),
          controller.obx(
            (data) {
              List<EvaluationLevelChart> chartData = [];
              if (controller.quickReviewOverviewResult.value.icrLevel != null) {
                if (_levelStandard == 'ICR') {
                  controller.quickReviewOverviewResult.value.icrLevel
                      ?.forEach((item) {
                    EvaluationLevelChart chart = EvaluationLevelChart(
                      item.level.toString(),
                      0,
                      item.speakingScore?.toDouble(),
                      item.speakingAiScore! / 10,
                      0,
                      item.writingScore?.toDouble(),
                      item.translateScore! / 10,
                    );
                    chartData.add(chart);
                  });
                }
              }
              return Container(
                margin: EdgeInsets.symmetric(vertical: 12.0),
                padding: EdgeInsets.symmetric(horizontal: 21.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(9.0),
                  color: Get.isDarkMode
                      ? AppTheme.colors.darkTheme2.withOpacity(0.6)
                      : Colors.white.withOpacity(0.3),
                ),
                child: EvaluationLevelStackedLines(
                  levelChartData: chartData,
                  chartTitle: 'Class Average'.tr,
                  xLabel: 'Score'.tr,
                  yLabel: '',
                  levelStandard: _levelStandard,
                  mode: 'quickView',
                ),
              );
            },
            onEmpty: Text('Data not available ...'.tr),
            //onLoading: Center(child: CircularProgressIndicator()),
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(9.0),
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2.withOpacity(0.6)
                  : Colors.white.withOpacity(0.3),
            ),
            child: controller.obx(
              (data) {
                List<EvaluationLevelChart> chartData = [];
                if (_levelStandard == 'ICR' &&
                    controller.quickReviewOverviewResult.value.icrLevel !=
                        null) {
                  controller.quickReviewOverviewResult.value.icrLevel
                      ?.forEach((item) {
                    EvaluationLevelChart chart = EvaluationLevelChart(
                      item.level.toString(),
                      0,
                      item.speakingScore?.toDouble(),
                      item.speakingAiScore! / 10,
                      0,
                      item.writingScore?.toDouble(),
                      item.translateScore! / 10,
                    );
                    chartData.add(chart);
                  });
                }
                return EvaluationStackedLineChart(
                  studentLists: _selectedStudentLists,
                  levelChartData: chartData,
                  chartTitle: 'Speaking'.tr,
                  xLabel: 'Score'.tr,
                  yLabel: '',
                  levelStandard: _levelStandard,
                );
              },
              onEmpty: Text('Data not available ...'.tr),
              //onLoading: Center(child: CircularProgressIndicator()),
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.0),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(9.0),
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2.withOpacity(0.6)
                  : Colors.white.withOpacity(0.3),
            ),
            child: controller.obx(
              (data) {
                List<EvaluationLevelChart> chartData = [];
                if (_levelStandard == 'ICR' &&
                    controller.quickReviewOverviewResult.value.icrLevel !=
                        null) {
                  controller.quickReviewOverviewResult.value.icrLevel
                      ?.forEach((item) {
                    EvaluationLevelChart chart = EvaluationLevelChart(
                      item.level.toString(),
                      0,
                      item.speakingScore?.toDouble(),
                      item.speakingAiScore! / 10,
                      0,
                      item.writingScore?.toDouble(),
                      item.translateScore! / 10,
                    );
                    chartData.add(chart);
                  });
                }

                return EvaluationStackedLineChart(
                  studentLists: _selectedStudentLists,
                  levelChartData: chartData,
                  chartTitle: 'Writing'.tr,
                  xLabel: 'Score'.tr,
                  yLabel: '',
                  levelStandard: _levelStandard,
                );
              },
              onEmpty: Text('Data not available ...'.tr),
              //onLoading: Center(child: CircularProgressIndicator()),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(9.0),
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2.withOpacity(0.6)
                  : Colors.white.withOpacity(0.3),
            ),
            child: controller.obx(
              (data) {
                List<EvaluationLevelChart> chartData = [];
                if (_levelStandard == 'ICR' &&
                    controller.quickReviewOverviewResult.value.icrLevel !=
                        null) {
                  controller.quickReviewOverviewResult.value.icrLevel
                      ?.forEach((item) {
                    EvaluationLevelChart chart = EvaluationLevelChart(
                      item.level.toString(),
                      0,
                      item.speakingScore?.toDouble(),
                      item.speakingAiScore! / 10,
                      0,
                      item.writingScore?.toDouble(),
                      item.translateScore! / 10,
                    );
                    chartData.add(chart);
                  });
                }

                return EvaluationStackedLineChart(
                  studentLists: _selectedStudentLists,
                  levelChartData: chartData,
                  chartTitle: 'AI Speaking'.tr,
                  xLabel: 'Score'.tr,
                  yLabel: '',
                  levelStandard: _levelStandard,
                );
              },
              onEmpty: Text('Data not available ...'.tr),
              //onLoading: Center(child: CircularProgressIndicator()),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(9.0),
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2.withOpacity(0.6)
                  : Colors.white.withOpacity(0.3),
            ),
            child: controller.obx(
              (data) {
                List<EvaluationLevelChart> chartData = [];
                if (_levelStandard == 'ICR' &&
                    controller.quickReviewOverviewResult.value.icrLevel !=
                        null) {
                  controller.quickReviewOverviewResult.value.icrLevel
                      ?.forEach((item) {
                    EvaluationLevelChart chart = EvaluationLevelChart(
                      item.level.toString(),
                      0,
                      item.speakingScore?.toDouble(),
                      item.speakingAiScore! / 10,
                      0,
                      item.writingScore?.toDouble(),
                      item.translateScore! / 10,
                    );
                    chartData.add(chart);
                  });
                }

                return EvaluationStackedLineChart(
                  studentLists: _selectedStudentLists,
                  levelChartData: chartData,
                  chartTitle: 'Translating'.tr,
                  xLabel: 'Score'.tr,
                  yLabel: '',
                  levelStandard: _levelStandard,
                );
              },
              onEmpty: Text('Data not available ...'.tr),
              //onLoading: Center(child: CircularProgressIndicator()),
            ),
          ),
        ],
      ),
    );
  }
}
